﻿using Commons.Helpers;
using Commons.Responses;
using EntityModels.E04.Interactions;
using IRepositories;
using Microsoft.EntityFrameworkCore;
using ORM;

namespace Repositories
{
    public class CommentRepository : BaseRepository<int, Comment>, ICommentRepository
    {
        public CommentRepository(PSPDbContext context) : base(context)
        {
           
        }
        public async Task<List<Comment>> GetCommentsByPhotographIdAsync(int pageIndex, int pageSize, string photographId)
        {
            var dbSet = Context.Set<Comment>().Include(x=>x.AppUser).Include(x=>x.Photograph).Where(x=>x.PhotographId == Guid.Parse(photographId) && x.ParentCommentId == null).OrderByDescending(c => c.LikeCount);
            if (pageSize <= 0)
            {
                pageSize = 100;
            }
            var datas = await dbSet.Skip((pageIndex-1)*pageSize).Take(pageSize).ToListAsync();

            return datas;
        }

        public async Task<List<Comment>> GetRepliesByCommentIdAsync(int commentId)
        {
            return await Context.Comments
                .Where(c => c.ParentCommentId == commentId)
                .ToListAsync();
        }

        public async Task<MessageResponse> IncreaseLikeAsync(int commentId)
        {
            var data = await GetAsync(commentId);
            if (data == null)
            {
                throw new CustomException("当前评论已删除!");
            }

            data.IncreaseLike();
            return await UpdateAsync(data);
        }

        public async Task<MessageResponse> ReduceLikeAsync(int commentId)
        {
            var data = await GetAsync(commentId);
            if (data == null)
            {
                throw new CustomException("当前评论已删除!");
            }

            data.ReduceLike();
            return await UpdateAsync(data);
        }
    }
}
